import React from 'react';  
import ReactDOM from 'react-dom';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {connect} from 'react-redux';
import * as actionCreators from '../action_creators';
import FolderStore from "../stores/FolderStore";
const TreeNode = React.createClass({
    mixins: [PureRenderMixin],
    getInitialState: function() {           
        var node = this.props.node;     
        var singleSelect =  this.props.option.hasOwnProperty("singleSelect") ? this.props.option.singleSelect : true;
        var editable = this.props.option.hasOwnProperty("editable") ? this.props.option.editable: false;
        var enableSelect = this.props.option.hasOwnProperty("enableSelect") ? this.props.option.enableSelect: false;
        return {
            expanded: !singleSelect,
            selected: false,
            editable: editable,
            singleSelect: singleSelect,
            enableSelect: enableSelect,
            isMounting: false,
        };
    },
    toggleExpanded: function(event) {
        if (!this.state.isMounting) return;
        this.expanded(!this.state.expanded);         
        if (event){
            event.stopPropagation();
        }     
    },
    expanded: function(bExpanded){          
        if (!this.state.isMounting) return;
        if (bExpanded && this.props.parent){              
            this.props.parent.expanded(bExpanded);
        }
        this.setState({ expanded: bExpanded });      
    },
    selected: function(selected){
        if (!this.state.isMounting) return;
        if (this.state.singleSelect) {
            var oldSelectedItem = this.props.tree.oldSelectedItem;                
            if (selected) {
                if (oldSelectedItem && oldSelectedItem !== this) {
                    oldSelectedItem.toggleSelected();
                }
                this.props.tree.oldSelectedItem = this;
            } else {
                if (oldSelectedItem && oldSelectedItem === this) {
                    this.props.tree.oldSelectedItem = null;
                }
            }
        }
        if (selected){
            this.props.tree.addSelectedItem(this);
        }
        else{
            this.props.tree.removeSelectedItem(this);
        }                    
        this.setState({
            selected: selected
        });     
    },
    toggleSelected: function() {            
        var selected = !this.state.selected;   
        this.selected(selected); 
    },
    componentWillReceiveProps: function(nextProps) {           
    },

    removeFolder: function(event) {
        window.removeFolder(this.props.node);          
        event.stopPropagation(); 
    },
    componentDidMount: function(){    
        var _this = this;    
        $(ReactDOM.findDOMNode(_this.props.tree)).on("selectNode_inner", function(event, data){             
            if(_this.props.node.id == data.id && !_this.state.selected){
                _this.expanded(true);
                _this.selected(true);                  
            }   
            event.stopPropagation();        
        });

        $(ReactDOM.findDOMNode(_this.props.tree)).on("expandNode_inner", function(event, data){
            if(_this.props.node.id == data.id){
                _this.expanded(true);                                 
            }   
            event.stopPropagation();        
        });

        this.state.isMounting = true;
    },
    componentWillUnmount:function() {  
        this.selected(false);      
        this.state.isMounting = false;   
    }, 
    handleClick : function(event) {      
        if (this.state.singleSelect){    
            this.toggleExpanded();
        }           
        this.toggleSelected();    
        var _this = this;      

        this.props.tree.onClickNode(this.props.node);  
        // event.stopPropagation(); //不能删除
    },
    render: function () {        
        var node = this.props.node;          
        var childrenItem = [];
        var _this = this;
        if (node.get("children")) {          
            node.get("children").forEach((node, index) => {
                if (node.get("type") == "cmis:folder"){
                    childrenItem.push(<TreeNode node={node} option={this.props.option} tree={this.props.tree} parent = {this} key={node.get("id")}/>); 
                }
            }); 
        }
                
        var check = this.state.enableSelect && this.state.selected && this.state.singleSelect;
        var iconNode = null;
        if (childrenItem.length > 0) {    
            iconNode = classNames({                 
                'fa-folder': !this.state.expanded && !check,
                'fa-folder-open': this.state.expanded && !check,
                'fa-check' : check,
            }, 'fa');                        
        }
        else {          
            iconNode = classNames({                 
                'fa-folder': this.props.option.style == 'tree-solid-line' && !check,
                'tree-dot': this.props.option.style != 'tree-solid-line' && !check,
                'fa-check' : check,
                'hide' : !this.state.singleSelect
            }, 'fa');  
        }


        var iconSelected = {
            'fa' : true,
            'fa-check' : this.state.selected,
            'fa-square-o' : !this.state.selected,
            'hide' : this.state.singleSelect
        }           
     
        var classes = {
            'tree-selected' : this.state.selected,         
        }

        //console.log("render", this.props.node.name, this.state.expanded)
        var editActionItem;
        if (this.state.editable){
           editActionItem = (<div className="tree-actions"><li onClick={_this.removeFolder} className ="fa fa-trash-o" name={"delete"}></li></div> )
        }

        if (childrenItem.length > 0){
            return (
                <div className={'tree-folder'} id ={node.id}>
                    <div ref='header' onClick={this.handleClick} className = {classNames(classes, "tree-folder-header")}>
                        <i className={iconNode} onClick={this.toggleExpanded}></i><i style={{width: '13px', marginLeft: '2px'}} onClick={this.toggleSelected} className={classNames(iconSelected)}></i>
                        <div className="tree-folder-name">{node.get("name")}</div>
                    </div>
                    <div className="tree-folder-content" style={{display : !this.state.expanded ? 'none': ''}}>{childrenItem}</div>      
                    
                </div>
            );
        }
        else{
            return (
                <div ref="item" id ={node.id} onClick={this.handleClick} className={classNames(classes,'tree-item word-break break-word')}>
                    <i className={iconNode}></i><i style={{width: '13px', marginLeft: '2px'}} onClick={this.toggleSelected} className={classNames(iconSelected)}></i>
                    <div className="tree-item-name ">{node.get("name")}</div> {editActionItem}
                </div>
            );
        }
    }
});
   
export const FolderTree = React.createClass({       
    getInitialState: function () {
        return {
           selectedNode : {},
           oldSelectedItem : null,          
        };
    },       
    onCurFolderChanged: function(event, curFolder){
        var _this = this;            
        if (!curFolder) return;
        _this.state.selectedNode = {}
        // _.each(_this.state.selectedNode, function(selecteItem){
        //     selecteItem.selected(false);
        // })   

        $(ReactDOM.findDOMNode(_this)).trigger("selectNode_inner", curFolder);
    },
    componentDidMount: function(){                
        var _this = this;   
        FolderStore.curFolderChanged(this.onCurFolderChanged);                  
        $(ReactDOM.findDOMNode(this)).data("getSelectedNode", function(){       
            var ret = [];
            _.each(_this.state.selectedNode, function(selecteItem){
                ret.push(selecteItem.props.node)
            })       
            return ret;                    
        })           
    },
    componentWillUnmount:function() {    
        FolderStore.curFolderChanged(this.onCurFolderChanged, false);         
    }, 
    componentWillReceiveProps : function(nextProps) {   
       /* _.each(this.state.selectedNode, function(selectedItem){
            selectedItem.toggleSelected();
        });        
        this.state.oldSelectedItem = null;   */           
    },
    expandNode : function(node){
        $(ReactDOM.findDOMNode(this)).trigger("expandNode_inner", node);
    },
    addSelectedItem: function(item){            
        this.state.selectedNode[item.props.node.id] = item;
    },
    removeSelectedItem: function(item){
        delete this.state.selectedNode[item.props.node.id];
    },
    onClickNode : function(node){
        this.props.onClickNode(node);
    },
    render: function () {                 
        var option = this.props.option;       
        var className = "tree " + this.props.option.style;
        var node = this.props.folderTree;          
        var children = [];
        var _this = this;
        if (node.get("children")) {     
            node.get("children").forEach((node, index)=>{
                if (node.get("type") == "cmis:folder"){
                    children.push(<TreeNode node={node} option={option} tree={this} key={node.get("id")}/>); 
                }
            })   
        }
        var rootItem = (<TreeNode node={node} option = {option} tree={_this}  key={node.id}/>)
        return (
            <div id={this.props.option.id} style={{"height": "100%"}} className={className}>
                {option.showRoot ? rootItem : children}
            </div>
        )
    }
});

function mapStateToProps(state) {
  return {
    folderTree: state.getIn(['folderTree']),  
  };
}

export const FolderTreeContainer = connect(
  mapStateToProps,
  actionCreators
)(FolderTree);
    